
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *
 * Used to do an api call to the google.com maps interface Returns the timezone
 * offset for a location
 *
 * @author Arun Lee, Michael Terada, Marek Lopez
 */
public class Timezone {

    String dstOffset;
    String rawOffset;
    String status;
    String timeZoneName;
    String timeZoneId;

    /**
     * Json returns: {"dstOffset":0.0, "rawOffset":-28800.0, "status":"OK",
     * "timeZoneId":"America/Los_Angeles", "timeZoneName":"Pacific Standard
     * Time"}
     *
     * @param latitude
     * @param longitude
     * @return
     */
    public Timezone(String latitude, String longitude) {

        String baseurl = "https://maps.googleapis.com/maps/api/timezone/";
        String currenturl;

        try {
            currenturl = baseurl + "json?location=" + latitude + "," + longitude + "&timestamp=1331161200&sensor=false";
            URL url = new URL(currenturl);
            BufferedReader buffreader = new BufferedReader(new InputStreamReader(
                    ((HttpURLConnection) url.openConnection()).getInputStream(), "UTF8"));

            JsonObject jsonObject = new JsonParser().parse(buffreader).getAsJsonObject();

            this.dstOffset = jsonObject.get("dstOffset").toString();
            this.rawOffset = jsonObject.get("rawOffset").toString();
            this.status = jsonObject.get("status").toString();
            this.timeZoneName = jsonObject.get("timeZoneName").toString();
            this.timeZoneId = jsonObject.get("timeZoneId").toString();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @return offset from UTC in seconds
     */
    public double getRawOffset() {
        double raw = -1;
        try {
            raw = Double.parseDouble(this.rawOffset);
        } catch (Exception e) {
            //Should check that we have a value for raw offset before calling.
        }
        return raw;
    }

    /**
     * example "Pacific Standard Time"
     *
     * @return string form time zone name
     */
    public String getTimeZoneName() {
        return timeZoneName;
    }

    /**
     * Example "America/Los_Angeles",
     *
     * @return string form time zone id
     */
    public String getTimeZoneId() {
        return timeZoneId;
    }
}